<?php
require_once(dirname(__FILE__) ."/File.php");
/*
 * Here is an example
 * <code>
 * $importFields = array("email", "name", "lastname", "birthdate", "gender");
 * $importToTable = "test";
 *
 * // I catch the posted file
 * $image = new Image();
 * if ($image->catchPost($_FILE['image'])!=UPLOAD_ERR_OK)
 *     die($image->_error($image->getErrorMessage()));
 *
 * // I see if the posted file is ok and a supported file format
 * if (!$image->savePost())
 *     die($image->_error($image->getErrorMessage()));
 *
 * // Saving the main image and resizing
 * if (!$image->resize($image->width/2, $image->height/2, 100))
 *     die($image->_error($image->getErrorMessage());
 *
 * // Creating the thumbnail
 * $imageThumb = $image->createThumbnail($image->width/4, $image->height/4, "thumb-". $image->filename, '', false, 100));
 */
class Image extends File
{
    public $mime="";
    public $width=0;
    public $height=0;
    public $attr="";
    public $style;
    public $cropName="";

    public function load()
    {
        if (file_exists($this->getPath()))
        {
            $this->size = filesize($this->getPath());
            list($this->width, $this->height, $type, $this->attr) = getimagesize($this->getPath());
            switch($type)
            {
                case 1: $this->type="gif"; break;
                case 2: $this->type="jpg"; break;
                case 3: $this->type="png"; break;
                case 4: $this->type="swf"; break;
                case 5: $this->type="psd"; break;
                case 6: $this->type="bmp"; break;
                default: $this->_error("Usuported image type");
                         return 0;
            }
            return 1;
        }
        else
        {
            $this->width=0;
            $this->height=0;
            $this->type="";
            $this->attr="";
        }
        return 0;
    }

    function fitInArea($maxWidth=0, $maxHeight=0, $quality=80)
    {
        // casting
        $maxWidth = (int)$maxWidth;
        $maxHeight = (int)$maxHeight;
        $quality = is_int($quality)? $quality : 80;

        $resizeCoef = 1;
        $resizeX = (float)$maxWidth/(float)$this->width;
        $resizeY = (float)$maxHeight/(float)$this->height;
        $resizeY = $resizeY ? $resizeY : 1;
        $resizeX = $resizeX ? $resizeX : 1;
        $resizeCoef = ($resizeX < $resizeY) ? $resizeX : $resizeY;
        $newWidth = (float)($this->width*$resizeCoef);
        $newHeight = (float)($this->height*$resizeCoef);
        return $this->resize($newWidth, $newHeight, $quality);
    }

    // Only works if it is a png|jpg|gif file!
    function resize($maxWidth=0, $maxHeight=0, $quality=80)
    {
        // casting
        $maxWidth = (int)$maxWidth;
        $maxHeight = (int)$maxHeight;
        $quality = is_int($quality)? $quality : 80;

        // creating image
        switch($this->type)
        {
            case "png": $img = imagecreatefrompng($this->getpath()); break;
            case "jpg": $img = imagecreatefromjpeg($this->getpath()); break;
            case "gif": $img = imagecreatefromgif($this->getpath()); break;
            default:
                $this->_error("unsuported type to resize");
                return 0;
        }

        if(isset($maxWidth) && isset($maxHeight) && $maxWidth > 0 && $maxHeight > 0)
        {
            $newWidth = $maxWidth;
            $newHeight = $maxHeight;
        }
        else
        {
            if(isset($maxWidth) && $maxWidth > 0)
            {
                $newWidth = $maxWidth;
                $newHeight = ((int)($newWidth * $this->height) / $this->width);
            }
            else
            {
                if(isset($maxHeight) && $maxHeight > 0)
                {
                    $newHeight = $maxHeight;
                    $newWidth = ((int)($newHeight * $this->width) / $this->height);
                }
                else
                {
                    $newHeight = $this->height;
                    $newWidth = $this->width;
                }
            }
        }

        $imgResource = imagecreatetruecolor($newWidth, $newHeight);
        imagecopyresampled($imgResource, $img, 0,0,0,0, $newWidth, $newHeight, $this->width, $this->height);

        switch($this->type)
        {
            case "jpg": $img = imagejpeg($imgResource, $this->getpath(), $quality); break;
            case "png":
                // png quality goes from 0 to 9 instead of 0 from 100 like jpg
                $quality=floor($quality/10);
                $img = imagepng($imgResource, $this->getpath(), $quality); break;
            case "gif":
                // quality option avoided...
                $img = imagegif($imgResource, $this->getpath()); break;
            default: return 0;
        }

        imagedestroy($imgResource);
        $this->load(); // I reload the image.
        return 1;
    }

    public function printHTML($opts=array())
    {
        echo $this->getHTML($opts);
    }

    public function getHTML($opts=array())
    {
        $opts["attr"] = $opts["attr"]? $opts["attr"] : $this->attr;
        $opts["style"] = $opts["style"]? $opts["style"] : $this->style;
        return file_exists($this->getPath() )? "<img src=\"". $this->getUrl() ."\" ". $opts["attr"] ." ". ($opts["style"]? "style=\"". $opts["style"] ."\"" : "") .">" : "";
    }

    /*
    * createThumbnail!
    * Only works if it is a png|jpg|gif file!
    */
    function &createThumbnail($maxWidth, $maxHeight, $thumbnailName, $newDir='', $fitInArea = false, $quality=80)
    {
        // casting
        $maxWidth = (int)$maxWidth;
        $maxHeight = (int)$maxHeight;
        $quality = is_int($quality)? $quality : 80;
        $thumbnailDir = $newDir? $newDir : $this->dirPath;

        if (!copy($this->getPath(), $thumbnailDir ."/". $thumbnailName))
        {
            $this->_error("error al crear el thumbnail");
            return 0;
        }
        $this->load();

        $thumbnail = new Image();
        $thumbnail->dirPath = $thumbnailDir;
        $thumbnail->filename = $thumbnailName;
        $thumbnail->load();
        $thumbnail->height = $this->height;
        $thumbnail->width = $this->width;

        if($fitInArea) $valid = $thumbnail->fitInArea($maxWidth, $maxHeight);
        else $valid = $thumbnail->resize($maxWidth, $maxHeight, $quality);

        if (!$valid)
        {
            $this->_error($thumbnail->getErrorMessage());
            $thumbnail->delete();
            unset($thumbnail);
            return 0;
        }
        return $thumbnail;
    }

    /* Crops an image*/
    function &cropImage($imageToCrop, $cropWidth, $cropHeight, $startWith, $startHeight, $containerWidth=67, $containerHeight=50)
    {

        list($imagewidth, $imageheight, $imageType) = getimagesize($imageToCrop); // List image properties
        $imageType = image_type_to_mime_type($imageType);
        $newImage = imagecreatetruecolor($containerWidth ,$containerHeight);

        switch($imageType)
        {
            case "image/gif":
                $source=imagecreatefromgif($imageToCrop); break;
            case "image/pjpeg":
            case "image/jpeg":
            case "image/jpg":
                $source=imagecreatefromjpeg($imageToCrop); break;
            case "image/png":
            case "image/x-png":
                $source=imagecreatefrompng($imageToCrop); break;
            default: return 0;
        }

        imagecopyresampled($newImage,$source,0,0,$startWith,$startHeight,$containerWidth ,$containerHeight,$cropWidth,$cropHeight);

        switch($imageType)
        {
            case "image/gif":
                imagegif($newImage,$this->getDirCropImage()); break;
            case "image/pjpeg":
            case "image/jpeg":
            case "image/jpg":
                imagejpeg($newImage,$this->getDirCropImage()); break; // Quality default 75
            case "image/png":
            case "image/x-png":
                imagepng($newImage,$this->getDirCropImage(), 7); break; // Quality default 9
            default: return 0;
        }

        return $this->cropName;
    }

    function deleteCropImage()
    {
        return unlink($this->getDirCropImage());
    }

    function getDirCropImage()
    {
        return $this->dirPath."/".$this->cropName;
    }

    function getUrlCropImage()
    {
        return $this->urlPath."/".$this->cropName;
    }

    function getHeight() {
        $size = getimagesize($this->getPath());
        $height = $size[1];
        return $height;
    }

    function getWidth() {
        $size = getimagesize($this->getPath());
        $width = $size[0];
        return $width;
    }

    function setCropName($name)
    {
        $this->cropName = $name;
    }

    public function existCrop()
    {
        if (file_exists($this->getDirCropImage())) return 1;
        return 0;
    }

}
?>
